package com.zipking.cloud.springbootmybatis.util.excel;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class  ExcelExport<T> {
    private final DataReader<T> reader;
    private final DataWriter<T> writer;

    public ExcelExport(DataReader<T> reader, DataWriter<T> writer) {
        this.reader = reader;
        this.writer = writer;
    }

    public void export(int threadNum, int pageSize) {
        ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
        CountDownLatch countDownLatch = new CountDownLatch(threadNum);

        for (int i = 0; i < threadNum; i++) {
            final int threadIndex = i;
            executorService.execute(() -> {
                int pageNum = threadIndex + 1;
                List<T> data = reader.readData(pageNum, pageSize);
                while (data != null && !data.isEmpty()) {
                    writer.writeData(pageNum, data);
                    pageNum += threadNum;
                    data = reader.readData(pageNum, pageSize);
                }
                countDownLatch.countDown();
            });
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}

